package com.falcon.file.storage.impl;

import com.falcon.file.domain.po.FileContentPO;
import com.falcon.file.mapper.IFileContentMapper;
import com.falcon.file.storage.IFileStorage;
import com.swan.core.exception.SwanBaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author zongf
 * @since 2023-05-25
 **/
@Slf4j
public class FileDbStorage implements IFileStorage {

    @Autowired
    private IFileContentMapper fileContentMapper;

    @Override
    public String write(MultipartFile file) {
        String content = null;

        try {
            content = new String(file.getBytes());
        } catch (Exception exception) {
            throw new SwanBaseException();
        }

        FileContentPO fileContentPO = new FileContentPO();
        fileContentPO.setContent(content);
        this.fileContentMapper.insertNotNull(fileContentPO);
        return String.valueOf(fileContentPO.getId());
    }

    @Override
    public void read(String storageId, OutputStream os) {

        Long contentId = Long.valueOf(storageId);

        FileContentPO fileContentPO = this.fileContentMapper.selectById(contentId);

        try {
            os.write(fileContentPO.getContent().getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new SwanBaseException();
        }

    }
}
